package com.treeengine.game.graphics;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

import com.treeengine.game.IGame;
import com.treeengine.game.io.IFileIO;

public class Texture {
	Graphics graphics;
	IFileIO file;
	String fileName;
	int textureId;
	int minFilter;
	int magFilter;
	int width;
	int height;
	
	public Texture(IGame game, String fileName){
		graphics = game.getGraphics();
		file = game.getFileIO();
		fileName = fileName;
		load();
	}
	
	public void load(){
		GL10 gl = graphics.getGL();
		int[] textureIds = new int[1];
		gl.glGenTextures(1, textureIds, 0);
		textureId = textureIds[0];
		
		InputStream in = null;
		try{
			in = file.readAsset(fileName);
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			width = bitmap.getWidth();
			height = bitmap.getHeight();
			gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
			GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
			setFilters(GL10.GL_TEXTURE_2D,0);
		}catch(IOException e){
			throw new RuntimeException();
		}finally{
			if(in != null)
				try{ in.close(); } catch(IOException e) {}
		}
	}

	public void reload(){
		load();
		bind();
		setFilters(minFilter, magFilter);
		graphics.getGL().glBindTexture(GL10.GL_TEXTURE_2D, 0);
	}
	
	public void setFilters(int minFilter, int magFilter){
		this.minFilter = minFilter;
		this.magFilter = magFilter;
		GL10 gl = graphics.getGL();
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);

	}
	
	public void bind(){
		GL10 gl = graphics.getGL();
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
	}
	
	public void dispose(){
		GL10 gl = graphics.getGL();
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
		int[] textureIds = {textureId};
		gl.glDeleteTextures(1, textureIds, 0);
	}
	
}
